//引入样式
import "../../assets/css/normalize.less";
import "../../assets/css/reset.less";
import "../../assets/css/property.less";
import "../../assets/css/basic.less";

import "../../assets/fonts/font_kok358gumca/iconfont.css";
import "../../assets/fonts/font_iysuojan2xi/iconfont.css";

import "../course_train/course_train.less";

// 引入轻提示
import { toast } from "../../utils/toast";

//引入dom
import { $ } from "../../utils/dom";

// 引入请求接口
import { postSaveDataReq } from "../../api/course";

// 定义索引
let index = 0;
let fragments = JSON.parse(sessionStorage.getItem("fragments"));
let cur_time = Date.now(); //课程训练
/**
 * 开始播放
 */

//  console.log(fragments);

const autoPlay = () => {
	$("#video").play();
	$("#curSection").textContent = index + 1;
	$("#allSection").textContent = fragments.length;
	$("#videoTitle").textContent = fragments[index].title;
};
autoPlay();

/***
 *  自动切换到下一曲
 *
 */
$("#video").addEventListener("ended", () => {
	$("#nextBtn").click();
});

/**
 *点击切换下一曲
 */

$("#nextBtn").addEventListener("click", () => {
	++index;
	if (index >= fragments.length) return;
	$("#video").src =
		"http://fitness.h5.itsource.cn:3701" + fragments[index].videoUrl;
	autoPlay();
});

/**
 * 点击切换上一曲
 */
$("#prevBtn").addEventListener("click", () => {
	--index;
	if (index < 0) {
		index = 0;
		return;
	}
	$("#video").src =
		"http://fitness.h5.itsource.cn:3701" + fragments[index].videoUrl;
	autoPlay();
});

/**
 * 进度条
 */

$("#video").addEventListener("timeupdate", () => {
	$(".progress").style.width =
		($("#video").currentTime / $("#video").duration) * 100 + "%";
});

/***
 * 保存数据
 */

$("#pauseBtn").addEventListener("click", () => {
	$("#video").pause();
	$(".mask").classList.add("dblock");
});

/**
 * 继续播放
 */
$("#continue").addEventListener("click", () => {
	$(".mask").classList.remove("dblock");
	autoPlay();
});

/**
 * 停止播放
 */
$("#over").addEventListener("click", async () => {
	const params = {
		type: 2,
		duration: Math.floor((Date.now() - cur_time) / 1000),
		meter: Math.floor((Date.now() - cur_time) / 1000) * 1,
		calorie: Math.floor((Date.now() - cur_time) / 1000) * 20,
	};
	const res = await postSaveDataReq(params);
	let { errno, data } = res.data;

	if (errno === 0) {
		toast("保存成功");
		setTimeout(() => {
			location.href = "./course.html";
		}, 4000);
	} else {
		toast("保存失败");
	}
});
